/******************************************************************************
 *
 * Project:		mGameEngine
 * File:		lock.h
 * Author:		karooolek
 * Created on:	2009-02-27
 *
 ******************************************************************************/

#ifndef LOCK_H_
#define LOCK_H_

#ifdef _WIN32
#define WIN32_LEAN_AND_MEAN
#include <windows.h>
#else
#include <pthread.h>
#endif

/**
 * Lock for synchronizing threads.
 * Used to create critical sections of code - a code
 * that can be executed by only one thread at a time.
 */
class Lock
{
private:
#ifdef _WIN32
	/**
	 * Mutex.
	 */
	HANDLE _mutex;
#else
	/**
	 * Mutex
	 */
	pthread_mutex_t _mutex;
#endif

	/**
	 * Timeout.
	 */
	float _timeout;

public:
	/**
	 * Create lock with initial state.
	 * @param locked lock initial state.
	 * @param timeout lock timeout in seconds.
	 */
	Lock(bool locked = false, float timeout = 0.0f);

	/**
	 * Copy construtor.
	 * @param lock lock to copy.
	 */
	Lock(const Lock &lock);

	/**
	 * Destroy lock.
	 */
	~Lock();

	/**
	 * Get lock timeout.
	 * @return lock timeout.
	 */
	float getTimeout() const
	{
		return _timeout;
	}

	/**
	 * Set lock timeout.
	 * @param timeout timeout in seconds or negative for infinity.
	 */
	void setTimeout(float timeout)
	{
		_timeout = timeout;
	}

	/**
	 * Close lock.
	 * If lock is already closed program will wait until it opens.
	 */
	void lock();

	/**
	 * Try to close lock, until timeout value elapses.
	 * @return true if locking succeded, false otherwise.
	 */
	bool tryLock();

	/**
	 * Open lock.
	 */
	void unlock();
};

#endif // LOCK_H_
